import 'dart:convert';
import 'dart:io';

import 'package:changxindianzishangwu/cache/local_cache.dart';
import 'package:changxindianzishangwu/dao/my_function_dao.dart';
import 'package:changxindianzishangwu/dao/upload_file_dao.dart';
import 'package:changxindianzishangwu/http/base/http_urls.dart';
import 'package:changxindianzishangwu/model/dynamic_media_model.dart';
import 'package:changxindianzishangwu/model/user_info_model.dart';
import 'package:changxindianzishangwu/util/app_color.dart';
import 'package:changxindianzishangwu/util/colors.dart';
import 'package:changxindianzishangwu/util/medio/picker_method.dart';
import 'package:changxindianzishangwu/util/toast.dart';
import 'package:changxindianzishangwu/widget/app_bar.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:get/get.dart' as gets;

///意见反馈
class FeedBackPage extends StatefulWidget {
  final String title;

  FeedBackPage(this.title);

  @override
  State<StatefulWidget> createState() {
    return new _FeedBackPageState();
  }
}

class _FeedBackPageState extends State<FeedBackPage> {
  //选择对象集合
  List<AssetEntity> assets = [];

  int get assetsLength => assets.length;

  //是否显示"添加"按钮
  bool isAdd = true;

  UserInfo _userInfo;

  //输入框监听
  TextEditingController _controller;
  TextEditingController _phoneController;

  @override
  void initState() {
    super.initState();
    _userInfo = getUserInfo();
    _controller = TextEditingController();
    _phoneController = TextEditingController();
  }

  @override
  void dispose() {
    EasyLoading.dismiss();
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    TextStyle textStyle =
        TextStyle(color: AppColor.colorDefaultText, fontSize: sp(14));
    return Scaffold(
      // backgroundColor: Colors.black26,
      appBar: TopAppBar(context, "意见反馈", isRightTextBtn: true, rightText: "提交",
          rightCallback: () {
        print('上传内容：列表:${assets.length}');
        if (EasyLoading.isShow) {
          return;
        }

        if (assets.length > 0) {
          //图片传输 有addimage
          EasyLoading.show(status: "正在发布图片...");
          _getAssetsFile();
          return;
        }

        if (_controller.text.isEmpty) {
          showToast("请输入内容~");
          return;
        }
        EasyLoading.show(status: "正在发布纯文本...");
        _releaseFeedBack("");
      }, leftCallBack: () {
            if (assets.isEmpty  && _controller.text.isEmpty) {
              Navigator.of(context).pop();
            } else
              showCupertinoDialog(
                  context: context, builder: (context) => getDialog(context));

      }),
      body: Container(
        color: Colors.white,
        child: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: Container(
                color: Colors.white,
                padding: EdgeInsets.all(15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      '反馈内容',
                      style: textStyle,
                    ),
                    TextField(
                      maxLength: 200,
                      controller: _controller,
                      maxLines: 6,
                      keyboardType: TextInputType.text,
                      style: textStyle,
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.zero,
                          hintText: "请输入...",
                          hintStyle: TextStyle(
                              color: AppColor.colorHintText, fontSize: sp(14)),
                          border: InputBorder.none),
                    ),
                  ],
                ),
              ),
            ),
            SliverToBoxAdapter(
              child: Container(
                color: AppColor.bg,
                height: 10,
              ),
            ),
            SliverToBoxAdapter(
              child: Padding(
                padding: const EdgeInsets.only(left: 18, top: 18),
                child: Text(
                  '添加图片(选填)',
                  style: textStyle,
                ),
              ),
            ),
            SliverSafeArea(
              sliver: SliverPadding(
                padding: EdgeInsets.all(15),
                sliver: SliverGrid(
                    delegate: SliverChildBuilderDelegate((context, index) {
                      return assetsLength == index && isAdd
                          ? _addImg()
                          : _item(index);
                    }, childCount: !isAdd ? assetsLength : assetsLength + 1),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        crossAxisSpacing: width(10),
                        mainAxisSpacing: width(10))),
              ),
            ),
            SliverToBoxAdapter(
              child: Container(
                color: AppColor.bg,
                height: 10,
              ),
            ),
            SliverToBoxAdapter(
              child: Container(
                color: Colors.white,
                padding: EdgeInsets.all(15),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      '电话号码',
                      style: textStyle,
                    ),
                    TextField(
                      maxLength: 11,
                      controller: _phoneController,
                      maxLines: 1,
                      keyboardType: TextInputType.number,
                      style: TextStyle(
                          color: AppColor.colorText85, fontSize: sp(12)),
                      decoration: InputDecoration(
                          contentPadding: EdgeInsets.zero,
                          hintText: "请输入...",
                          hintStyle: TextStyle(
                              color: AppColor.colorHintText, fontSize: sp(12)),
                          border: InputBorder.none),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///默认Add图片
  Widget _addImg() {
    return TextButton(
        style: ButtonStyle(
            backgroundColor: MaterialStateProperty.all(AppColor.colorGrey245)),
        onPressed: () {
          selectAssets();
        },
        child: Icon(
          Icons.add,
          color: AppColor.colorGrey193,
        ));
  }
  CupertinoAlertDialog getDialog(context) {
    return CupertinoAlertDialog(
        content: new SingleChildScrollView(
          child: ListBody(
            children: <Widget>[Text("提示"), Text("是否要返回？"), Text("当前页面内容不会被保存")],
          ),
        ),
        actions: <Widget>[
          CupertinoDialogAction(
            child: Text("确定"),
            onPressed: () {
              Navigator.of(context).pop();
              gets.Get.back();
            },
          ),
          CupertinoDialogAction(
            child: Text("取消"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ]);
  }
  bool isDisplayingDetail = true;

  Widget _item(int index) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 4.0, vertical: 4.0),
      child: AspectRatio(
        aspectRatio: 1,
        child: Stack(
          children: <Widget>[
            Positioned.fill(child: _selectedAssetWidget(index)),
            AnimatedPositioned(
              duration: kThemeAnimationDuration,
              top: isDisplayingDetail ? 6.0 : -30.0,
              right: isDisplayingDetail ? 6.0 : -30.0,
              child: _selectedAssetDeleteButton(index),
            ),
          ],
        ),
      ),
    );
  }

  Widget _selectedAssetWidget(int index) {
    final AssetEntity asset = assets.elementAt(index);
    return GestureDetector(
      onTap: isDisplayingDetail
          ? () async {
              final List<AssetEntity> result =
                  await AssetPickerViewer.pushToViewer(
                context,
                currentIndex: index,
                previewAssets: assets,
                themeData: AssetPicker.themeData(Color(0xff00bc56)),
              );
              if (result != null && result != assets) {
                assets = List<AssetEntity>.from(result);
                if (mounted) {
                  setState(() {
                    assets.length == 3 ? isAdd = false : isAdd = true;
                  });
                }
              }
            }
          : null,
      child: RepaintBoundary(
        child: ClipRRect(
          borderRadius: BorderRadius.circular(2.0),
          child: _assetWidgetBuilder(asset),
        ),
      ),
    );
  }

  Widget _assetWidgetBuilder(AssetEntity asset) {
    Widget widget;
    switch (asset.type) {
      case AssetType.audio:
        widget = _audioAssetWidget(asset);
        break;
      case AssetType.video:
        widget = _videoAssetWidget(asset);
        break;
      case AssetType.image:
      case AssetType.other:
        widget = _imageAssetWidget(asset);
        break;
    }
    return widget;
  }

  Widget _selectedAssetDeleteButton(int index) {
    return GestureDetector(
      onTap: () => removeAsset(index),
      child: DecoratedBox(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(5.0),
          color: Colors.white,
        ),
        child: Icon(
          Icons.close,
          color: Colors.grey,
          size: 15.0,
        ),
      ),
    );
  }

  void removeAsset(int index) {
    setState(() {
      assets.removeAt(index);
      if (assets.isEmpty) {
        isDisplayingDetail = false;
      }
      assets.length == 3 ? isAdd = false : isAdd = true;
    });
  }

  Widget _audioAssetWidget(AssetEntity asset) {
    return ColoredBox(
      color: Colors.red[200],
      child: Stack(
        children: <Widget>[
          AnimatedPositionedDirectional(
            duration: kThemeAnimationDuration,
            top: 0.0,
            start: 0.0,
            end: 0.0,
            bottom: isDisplayingDetail ? 20.0 : 0.0,
            child: Center(
              child: Icon(
                Icons.audiotrack,
                size: isDisplayingDetail ? 24.0 : 16.0,
              ),
            ),
          ),
          AnimatedPositionedDirectional(
            duration: kThemeAnimationDuration,
            start: 0.0,
            end: 0.0,
            bottom: isDisplayingDetail ? 0.0 : -20.0,
            height: 20.0,
            child: Text(
              asset.title ?? '',
              style: const TextStyle(height: 1.0, fontSize: 10.0),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              textAlign: TextAlign.center,
            ),
          ),
        ],
      ),
    );
  }

  Widget _imageAssetWidget(AssetEntity asset) {
    return Image(
      image: AssetEntityImageProvider(asset, isOriginal: false),
      fit: BoxFit.cover,
    );
  }

  Widget _videoAssetWidget(AssetEntity asset) {
    return Stack(
      children: <Widget>[
        Positioned.fill(child: _imageAssetWidget(asset)),
        ColoredBox(
          color: Colors.grey,
          child: Center(
            child: Icon(
              Icons.video_library,
              color: Colors.white,
              size: isDisplayingDetail ? 24.0 : 16.0,
            ),
          ),
        ),
      ],
    );
  }

  Future<void> selectAssets() async {
    final PickMethod model = PickMethod.image(3);

    final List<AssetEntity> result = await model.method(context, assets);
    if (result != null) {
      assets = List<AssetEntity>.from(result);
      if (mounted) {
        setState(() {
          assets.length == 3 ? isAdd = false : isAdd = true;
        });
      }
    }
  }

  _getAssetsFile() async {
    Iterable<Future<File>> files = assets.map((element) {
      return element.originFile;
    }).toList();

    await Future.wait(files).then((value) {
      _getMediaNetPath(value);
    });
  }

  ///上传图片到服务器
  _getMediaNetPath(assetsFile) async {
    FormData formData = FormData();
    //图片视频
    Iterable<MapEntry<String, MultipartFile>> maps =
        Iterable.generate(assetsFile.length, (index) {
      String path = "${assetsFile[index].absolute.path}";

      return MapEntry("files",
          MultipartFile.fromFileSync(path, filename: assets[index].title));
    });

    formData.files.addAll(maps);
    DynamicMediaModel value = await UpLoadFileDao.addFile(formData);
    if (value.resultCode == 1) {
      print('返回数据:${json.encode(value)}');
      _releaseFeedBack(json.encode(value.data.images));
    } else {
      showToast("媒体上传失败");
    }
  }

  void _releaseFeedBack(String asset) async {
    print('上传内容：${asset}');

    var dy = await MyFunctionDao.feedBack(
      _controller.text.toString().trim(),
      asset,
      _phoneController.text.toString().trim(),
      _userInfo.userId,
    );
    EasyLoading.dismiss();
    if (dy.resultCode == 1) {
      showToast("提交意见成功");
      Navigator.of(context).pop();
    } else {
      showToast("提交意见失败");
    }

  }

  CupertinoAlertDialog dialog = CupertinoAlertDialog(
      content: new SingleChildScrollView(
        child: ListBody(
          children: <Widget>[Text("提示"), Text("是否要返回？"), Text("当前页面就会失效")],
        ),
      ),
      actions: <Widget>[
        CupertinoDialogAction(
          child: Text("确定"),
          onPressed: () {},
        ),
        CupertinoDialogAction(
          child: Text("取消"),
          onPressed: () {},
        ),
      ]);
}
